package com.seelyn.ddvideo.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadThread implements Runnable {

    private Logger LOG = LoggerFactory.getLogger(DownloadThread.class);
    private String url;
    private File file;
    private int start;
    private int end;

    public DownloadThread(String url, File file, int start, int end) {
        this.url = url;
        this.file = file;
        this.start = start;
        this.end = end;
    }

    @Override
    public void run() {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Range", "bytes=" + start + "-" + end);
            RandomAccessFile accessFile = new RandomAccessFile(file, "rw");
            accessFile.seek(start);
            int code = connection.getResponseCode();
            if (code == 206) {
                InputStream is = connection.getInputStream();
                byte[] buffer = new byte[102400];
                int length;
                while ((length = is.read(buffer)) != -1) {
                    accessFile.write(buffer, 0, length);
                }
                connection.disconnect();
                accessFile.close();
            }
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }
}
